package com.mall.search.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.lucene.IKAnalyzer;

@Service
public class LuceneMallBuild {
	public final Version version = Version.LUCENE_4_9;
	// private Directory directory = new RAMDirectory();
	// private DirectoryReader ireader = null;
	// private IndexWriter iwriter = null;
	private IKAnalyzer analyzer;
	// 存放索引文件的位置，即索引库
	// private String searchDir = "d:\\Test\\Index";
	// private File indexFile = null;

	// /**
	// * 读取索引文件
	// *
	// * @return
	// * @throws Exception
	// */
	// public IndexSearcher getSearcher(String searchDir) throws Exception {
	// if (indexFile == null) {
	// indexFile = new File(searchDir);
	// }
	// if (ireader == null) {
	// ireader = DirectoryReader.open(FSDirectory.open(indexFile));
	// }
	//
	// return new IndexSearcher(ireader);
	// }

	/**
	 * 中文分词工具
	 * 
	 * @return
	 */
	public IKAnalyzer getAnalyzer() {
		if (analyzer == null) {
			return new IKAnalyzer();
		} else {
			return analyzer;
		}
	}

	/**
	 * 获取IndexWriter
	 * 
	 * @param searchDir
	 * @return
	 */
	public IndexWriter getIndexWriter(String searchDir) {
		IndexWriter iwriter = null;
		try {
			/**
			 * 获取索引文件位置
			 */
			File indexFile = new File(searchDir);
			if (!indexFile.exists()) {
				indexFile.mkdirs();
			}
			/**
			 * 设置索引参数
			 */
			Directory directory;
			directory = FSDirectory.open(indexFile);
			IndexWriterConfig iwConfig = new IndexWriterConfig(version, getAnalyzer());
			iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
			iwriter = new IndexWriter(directory, iwConfig);
			return iwriter;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 关闭IndexWriter
	 * 
	 * @param iwriter
	 */
	public void closeIndexWriter(IndexWriter iwriter) {
		if (iwriter != null) {
			try {
				iwriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
